<template>
  <Page title="每日打卡" :on-page-back="onPageBack">
    <template #navBarCustom>
      <view class=""></view>
    </template>
    <template #content>
      <div class="w-full h-full px-20px box-border flex flex-col">
        <!-- 学科列表 -->
        <subject-tabs
          class="py-16px"
          :tabs="subjects.list"
          :active="subjects.active"
          @change="subjects.onChange($event)"
        />
        <!-- 打卡任务列表 -->
        <scroll-view
          ref="scroll"
          class="flex-1 overflow-scroll"
          :refresher-enabled="true"
          :refresher-loader-offset-y="-16"
          @scrolltolower="tasks.getList(subjects.active)"
          @refresh="tasks.refresh($event)"
        >
          <task-list :list="tasks.list" @todo="tasks.todo($event)" />
          <load-more
            cssStyle="padding-top:0.14rem"
            :loading="tasks.loading"
            :has-more="tasks.hasMore"
            @click="tasks.getList(subjects.active)"
          />
        </scroll-view>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page'
import SubjectTabs from '@/components/subject/tabs'
import ScrollView from '@/components/scroll-view'
import TaskList from './components/task-list'
import LoadMore from '@/components/load-more'
import { getKpointPractice } from '@/api/exercise'
import { createRecommendUseRecord } from '@/api/wq-book'
import {
  getSubjectApi,
  getAppStudyClockinListApi,
  checkStudyClockinApi,
  goStudyClockinRecommendApi,
  goStudyClockinPracticeApi
} from '@/api/daily-attendance'
import { mapActions } from 'vuex'
import { debounce } from '@/utils'
import { MODULE_ID } from '@/store/modules/module-use'

export default {
  components: {
    Page,
    ScrollView,
    SubjectTabs,
    TaskList,
    LoadMore
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (from.params.completed) {
        const subjectId = vm.subjects.active
        vm.tasks.reset()
        vm.tasks.getList(subjectId)
      }
    })
  },
  data() {
    return {
      loading: null,
      taskIds: {},
      storageTaskIds: {},
      lastTaskId: '',
      // 学科栏目
      subjects: {
        vm: this._self,
        active: '',
        list: [],
        getList: async function (callback) {
          const { data = [] } = await getSubjectApi()
          const subjects = await this.vm.getDictByType('subject')

          const list = []
          data.forEach((i) => {
            const subject = subjects.find((s) => s.value == i)
            list.push({
              dictType: 'subject',
              label: subject.label,
              status: 0,
              value: subject.value
            })
          })

          // 如果没有开通的科目，弹出弹窗
          if (list.length === 0) {
            this.vm.$popup.show({
              type: 'alert',
              success: (popup) => {
                popup.$on('confirm', () => {
                  this.vm.$popup.hide('alert')
                  this.vm.$router.back()
                })
                popup.setData({
                  content: '没有已开通的科目'
                })
              }
            })
            return
          }

          list.unshift({
            dictType: 'subject',
            label: '全部',
            status: 0,
            value: ''
          })

          this.list = list.map((item) => {
            const { value: subjectId } = item
            subjectId &&
              this.vm.$storage.daily_attendance
                .getTaskIdsItem(subjectId)
                .then(({ success, data }) => {
                  success && (this.vm.storageTaskIds[subjectId] = data)
                })
            return item
          })
          callback('')
        },
        onChange: debounce(function (subjectId) {
          // 上传模块使用时间
          this.vm.$store.state.moduleUse.currentModuleUse.submit()
          // 重置
          this.vm.$store.state.moduleUse.currentModuleUse.onSubjectChange(subjectId)

          this.active = subjectId
          this.vm.tasks.reset()
          this.vm.tasks.getList(subjectId)
        }, 300)
      },
      // 打卡任务
      tasks: {
        vm: this._self,
        pageNo: 1,
        pageSize: 12,
        loading: true,
        hasMore: true,
        list: [],
        getList: async function (subjectId) {
          if (this.loading) return

          this.loading = true
          const tasks = this.list

          let params = {
            pageNo: this.pageNo,
            pageSize: this.pageSize
          }

          if (subjectId) params['subjectId'] = subjectId

          const {
            data: { list }
          } = await getAppStudyClockinListApi(params)

          if (list.length < this.pageSize) {
            this.hasMore = false
          }

          if (list.length > 0) {
            if (this.pageNo === 1 && !subjectId) {
              this.vm.lastTaskId = list[0].studyClockinId
            }

            const { taskIds } = this.vm

            tasks.push(
              ...list.map((item) => {
                const currentSubjectId = this.vm.subjects.active
                const { subjectId, studyClockinId } = item
                const storage_task_ids_item = this.vm.storageTaskIds[currentSubjectId]

                // 标记是否已读
                if (!currentSubjectId) {
                  item['unread'] = 1
                  for (let subjectId in this.vm.storageTaskIds) {
                    if (this.vm.storageTaskIds[subjectId].find((id) => id === studyClockinId)) {
                      item['unread'] = 0
                      break
                    }
                  }
                } else if (
                  storage_task_ids_item &&
                  storage_task_ids_item.find((id) => id === studyClockinId)
                ) {
                  item['unread'] = 0
                } else {
                  item['unread'] = 1
                }

                // 缓存id
                if (taskIds[subjectId]) {
                  const task_ids = taskIds[subjectId]
                  taskIds[subjectId] = Array.from(new Set(task_ids.concat(studyClockinId)))
                } else {
                  taskIds[subjectId] = [studyClockinId]
                }

                return item
              })
            )
            this.pageNo++
          }

          this.loading = false
        },
        refresh: async function (done = () => {}) {
          const currentSubjectId = this.vm.subjects.active
          const params = {
            pageNo: (this.pageNo = 1),
            pageSize: this.pageSize,
            subjectId: currentSubjectId ? currentSubjectId : undefined
          }

          const {
            data: { list }
          } = await getAppStudyClockinListApi(params)

          this.list.length = 0
          this.list.push(
            ...list.map((item) => {
              const { taskIds } = this.vm
              const { subjectId, studyClockinId } = item
              const storage_task_ids_item = this.vm.storageTaskIds[currentSubjectId]

              // 标记是否已读
              if (!currentSubjectId) {
                item['unread'] = 1
                for (let subjectId in this.vm.storageTaskIds) {
                  if (this.vm.storageTaskIds[subjectId].find((id) => id === studyClockinId)) {
                    item['unread'] = 0
                    break
                  }
                }
              } else if (
                storage_task_ids_item &&
                storage_task_ids_item.find((id) => id === studyClockinId)
              ) {
                item['unread'] = 0
              } else {
                item['unread'] = 1
              }

              // 缓存id
              if (taskIds[subjectId]) {
                const task_ids = taskIds[subjectId]
                taskIds[subjectId] = Array.from(new Set(task_ids.concat(studyClockinId)))
              } else {
                taskIds[subjectId] = [studyClockinId]
              }

              return item
            })
          )
          this.pageNo++

          done()
        },
        reset: function () {
          this.pageNo = 1
          this.pageSize = 12
          this.loading = false
          this.hasMore = true
          this.list = []
        },
        todo: async function (item) {
          const { studyClockinId, subjectId, kpointIds, type: studyClockinType } = item
          const kpointIdList = kpointIds ? kpointIds.split(',').filter((i) => i) : []

          // 加载动画
          const loading = this.vm.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.5)'
          })
          // 一分钟内加载不成功关闭loading弹窗
          const timer = setTimeout(() => {
            loading.close()
          }, 60000)

          // 获取打卡任务详情ID列表
          const { data: studyClockinList } = await checkStudyClockinApi({
            clockinId: studyClockinId,
            subjectId,
            kpointIds,
            type: studyClockinType === 1 ? 1 : 2
          })
          const detailIds = studyClockinList.map((item) => item.id)

          // 1 => 错题本 2 => 习题中心
          switch (studyClockinType) {
            case 1:
              // 去打卡
              const { data: nextQuestion, msg } = await goStudyClockinRecommendApi({
                subjectId,
                detailIds
              })

              if (!nextQuestion) {
                this.vm.$message.info(msg)
                // 关闭加载动画
                clearTimeout(timer)
                loading.close()
                return
              }

              // 创建举一反三练习记录
              const { data: recommendUseRecordId } = await createRecommendUseRecord({
                subjectId
              })

              // 去做题
              this.vm.$store.commit(
                'setDailyAttendanceCurrentTask',
                Object.assign(item, { detailIds })
              )

              const { practiceId, questionId } = nextQuestion
              this.vm.$store.commit('setCurrentPractice', {
                record: {
                  id: practiceId,
                  subject: subjectId,
                  questionId,
                  practiceName: '举一反三',
                  userKpointDataId: 0,
                  recommendUseRecordId,
                  kpointIds: kpointIdList
                },
                questions: [nextQuestion],
                questionIndex: 0
              })

              this.vm.$router.push(
                `/pages/daily-attendance/practice/xkw/index?studyClockinId=${studyClockinId}`
              )
              break
            case 2:
              // 去打卡
              const { data, msg: _msg } = await goStudyClockinPracticeApi({
                detailIds
              })

              if (!data) {
                this.vm.$message.info(_msg)
                // 关闭加载动画
                clearTimeout(timer)
                loading.close()
                return
              }

              const questions = data.map((item) => {
                // 学科id修正
                item.courseId = subjectId
                return item
              })

              // 获取练习record
              const { courseId, kpointIds, difficultyLevel } = questions[0] // 第一题
              const [kpointId] = JSON.parse(kpointIds)
              const { data: record } = await getKpointPractice({
                courseId,
                kpointId: kpointId + '',
                difficultyLevel,
                detailIds
              })

              // 去做题
              this.vm.$store.commit(
                'setDailyAttendanceCurrentTask',
                Object.assign(item, { detailIds })
              )

              this.vm.$store.commit('setCurrentPractice', {
                record: Object.assign(record, { kpointIds: kpointIdList }),
                questions,
                questionIndex: 0
              })

              this.vm.$router.push(
                `/pages/daily-attendance/practice/xkw/index?studyClockinId=${studyClockinId}`
              )
              break
            default:
              break
          }

          // 关闭加载动画
          clearTimeout(timer)
          loading.close()
        }
      }
    }
  },
  mounted() {
    this.$store.dispatch('initDailyAttendanceStorage')
    this.subjects.getList((subjectId) => {
      this.tasks.loading = false
      this.tasks.getList(subjectId)

      // 初始化模块使用记录
      this.$store.commit('setCurrentModuleUse', {
        vm: this._self,
        type: MODULE_ID.DAILY,
        subjectId
      })
    })
  },
  methods: {
    ...mapActions(['getDictByType']),
    onPageBack() {
      // 缓存作业id
      this.saveStorageTaskIds()
      // 发送最新的打卡任务id给安卓
      if (window.android && this.lastTaskId) {
        window.android.setlastTaskId(this.lastTaskId)
      }
      this.$router.back()
    },
    saveStorageTaskIds() {
      // 缓存taskIds
      const { taskIds, storageTaskIds } = this
      const newTaskIds = {}

      for (let subjectId in taskIds) {
        newTaskIds[subjectId] = taskIds[subjectId]
      }

      for (let subjectId in storageTaskIds) {
        if (newTaskIds[subjectId]) {
          const ids = newTaskIds[subjectId]
          newTaskIds[subjectId] = Array.from(new Set(storageTaskIds[subjectId].concat(ids)))
        } else {
          newTaskIds[subjectId] = storageTaskIds[subjectId]
        }
      }

      for (let subjectId in newTaskIds) {
        this.$storage.daily_attendance.getTaskIdsItem(subjectId).then(({ success }) => {
          if (success) {
            this.$storage.daily_attendance.putTaskIdsItem({
              subjectId,
              value: newTaskIds[subjectId]
            })
          } else {
            this.$storage.daily_attendance.setTaskIdsItem({
              subjectId,
              value: newTaskIds[subjectId]
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
